package com.unswift.cloud.feign.config;

import java.util.Enumeration;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiMethod;
import com.unswift.utils.ObjectUtils;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;

@Configuration
@Api(value="feign拦截器", author="unswift", date="2023-04-16", version="1.0.0")
public class FeignConfiguration {
	private final Logger log = LoggerFactory.getLogger(getClass());
	
	@Bean
	@ApiMethod(value="拦截器方法实现Bean")
	public RequestInterceptor requestInterceptor() {
		return new RequestInterceptor() {
			@Override
			public void apply(RequestTemplate requestTemplate) {
				HttpServletRequest request = getHttpServletRequest();
				boolean affix=false;
				if (request != null) {
					if(requestTemplate.headers()!=null && requestTemplate.headers().containsKey("Content-Type")){
						List<String> contentType=(List<String>)requestTemplate.headers().get("Content-Type");
						if(ObjectUtils.isNotEmpty(contentType)){
							if("multipart/form-data".equals(contentType.get(0))){
								affix=true;
							}
						}
						
					}
					Enumeration<String> enumeration = request.getHeaderNames();
					while (enumeration.hasMoreElements()) {
						String key = enumeration.nextElement();
						String value = request.getHeader(key);
						if(!key.equalsIgnoreCase("content-length")){
							requestTemplate.header(key, value);
						}
					}
				}
				requestTemplate.header("accept","*/*");
				if(!affix){
					requestTemplate.header("content-type","application/json");
				}
			}

			private HttpServletRequest getHttpServletRequest() {
				try {
					RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
					if (requestAttributes == null) {
						log.info("========RequestAttributes is null");
						return null;
					} else {
						return ((ServletRequestAttributes) requestAttributes).getRequest();
					}
				} catch (Exception e) {
					log.error(e.getMessage(), e);
					return null;
				}
			}
		};
	}
	
}
